package com.unbook.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Calendar;
import java.util.Map;

public class JwtUtils {
    private static final String SING = "ldjfklajsfjas";

    /**
     * 生成Token  header.payload.sign
     */
    public static <T> String getToken(T userId, int code, Map<String, String> data) {
        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.DATE, 7); //默认7天过期
        //创建jwt builder
        JWTCreator.Builder builder = JWT.create();

        //payload
        builder.withClaim("userId",userId.toString());
        builder.withClaim("code",code);
        data.forEach(builder::withClaim);

        return builder.withExpiresAt(instance.getTime())
                .sign(Algorithm.HMAC256(SING));
    }

    /**
     *  验证token的合法性
     */
    public static boolean verify(String token){
        try {
            JWT.require(Algorithm.HMAC256(SING)).build().verify(token);  //这一行代码就可以起到验证的作用，因为在验证不匹配时它自动会抛出异常
        }catch (Exception e){
            return false;
        }
        return true;
    }

    /**
     * 获取token的信息方法
     */
    public static DecodedJWT getTokenInfo(String token){
        DecodedJWT verify = JWT.require(Algorithm.HMAC256(SING)).build().verify(token);
        return verify;
    }
}
